package com.mimiwang.common.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author by guiwei
 * @Classname Jwt
 * @Description
 * @Date 2022/1/6 16:12
 */
public class JwtUtil {
    //密钥
    private static  String SECRET = "7^@(HDJsmd())_2y88cJ!#E@";


    /***
    * @Description: 获得一个token
    * @Param: [map]
    * @Return:  java.lang.String
    * @Author: guiwei
    * @Date: 2022/1/22 15:43
    */

    public static String getToken(Map<String,String> map){
        //生成一个builder对象 将heard,payload 存入
        JWTCreator.Builder builder = JWT.create();
        //payload
        for (String s : map.keySet()) {
            builder.withClaim(s,map.get(s));
        }
        //设置过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,3);
        builder.withExpiresAt(instance.getTime());
        String token = builder.sign(Algorithm.HMAC256(SECRET));
        return token;

    }
    /***
    * @Description: 验证token
    * @Param: [token]
    * @Return:  com.auth0.jwt.interfaces.DecodedJWT
    * @Author: guiwei
    * @Date: 2022/1/22 15:44
    */

    //验证token
    public static DecodedJWT tokenVerify(String token){
        //传入token进行验证
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
    //获取token中的payload
    public static Map<String, Claim> getPayloadFromToken(String token){
        Map<String, Claim> claims = null;
        try {
            claims = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaims();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return claims;
        }
    }
}
